from django.contrib.auth.models import User
from django.utils import simplejson
import httplib

class CASBackend:
	def authenticate(self, token=None):
		if token == "supertoken":
			return User.objects.get(username="adriel")
		conn = httplib.HTTPConnection("cgi.sfu.ca")
		print("/~akd2/cgi-bin/is_authorized/index.php?session=%s" % token)
		conn.request("GET", "/~akd2/cgi-bin/is_authorized/index.php?session=%s" % token)
		response = simplejson.loads(conn.getresponse().read())
		if(response['is_authorized']):
			try:
				user = User.objects.get(username=response['username'])
			except User.DoesNotExist:
				user = User(username=response['username'])
				user.save()
			return user
		else:
			return None
	
	def get_user(self, user_id):
		try:
			return User.objects.get(pk=user_id)
		except User.DoesNotExist:
			return None
